<template>
  <div class="w-full h-[80vh]" :class="isEdit == false ? 'h-[700px]' : 'h-[400px]'">
    <div v-if="isEdit" class="flex items-center gap-[5px]">
      <el-autocomplete v-model="search" :fetch-suggestions="querySearchAsync" value-key="name" placeholder="搜索标点"
        @select="onchange" />
      <el-button @click="createPolygon">
        {{ createArea ? "停止添加" : "添加区域" }}
      </el-button>
      <el-popover placement="bottom-start" :width="280">
        <template #default>
          <div class="demo-rich-conent flex flex-col gap-[10px]">
            <p>1.在输入框输入具体地址名称进行标点,标点后使用鼠标可移动标记点改变选择</p>
            <p>2.点击添加区域进行区域划定,新建区域后点击鼠标右键完成新增区域</p>
            <p>3.在已划定区域空白圆圈上单击鼠标左键删除点位,拖动圆圈可修改区域</p>
            <p>4.双击已选定地图区域可进行切换编辑区域</p>
          </div>
        </template>
        <template #reference>
          <el-icon color="#409eff">
            <QuestionFilled :size="60" />
          </el-icon>
        </template>
      </el-popover>
    </div>
    <div class="mt-[10px]"></div>
    <el-amap ref="amapRef" :show-label="true" :center="centerValue" :zoom="zoom" :doubleClickZoom="false" @init="init">
      <el-amap-mouse-tool v-if="createType" :type="createType" :showTooltip="false" :auto-clear="true" @draw="draw" />

      <template v-for="(polygon, index) in polygons">
        <el-amap-polygon v-model:path="polygon.path" :visible="polygon.visible" :editable="polygon.edit"
          :draggable="polygon.draggable" :strokeOpacity="polygon.strokeOpacity" :fillColor="polygon.fillColor"
          :strokeColor="polygon.strokeColor" :strokeWeight="polygon.strokeWeight" :fillOpacity="polygon.fillOpacity"
          :strokeDasharray="polygon.strokeDasharray" @adjust="addnode" @addnode="addnode" @removenode="addnode"
          @mouseover="mouseOver(index)" @mouseout="mouseOut(index)" @dblclick="dblclick(index)" />
      </template>

      <el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker.position" :draggable="false"
        @dragend="dragends" />

    </el-amap>
  </div>
</template>

<script setup lang="ts">

import { ref, reactive, watch } from "vue";
// import {ElAmap, ElAmapPolygon} from "@vuemap/vue-amap";
import { cloneDeep, isArray, isEqualArray } from "@pureadmin/utils";
import { QuestionFilled } from "@element-plus/icons-vue";
import { ElAmap, ElAmapPolygon, ElAmapMouseTool, ElAmapMarker } from "@vuemap/vue-amap";


const emits = defineEmits(['update:center', 'update:area'])

const props = defineProps({  //父子组件参数传递
  center: {
    type: [Array, Boolean]
  },
  area: {
    type: Array
  },
  zoom: {
    default: 12
  },

  isEdit: {
    type: Boolean
  },

})
console.log("选择的区域",props);

const mapData = reactive({
  fillColor: "#adea9f",
  hoverFillColor: "#7bccc4"
})
const createArea = ref(false) // 点击开始、停止添加区域
const place = ref([])// 下拉框的数据
const loading = ref(false)
const search = ref("") //搜索
const createType = ref("") //鼠标工具的类型
const polygons = ref([])  //区域数组
const paths = ref([])
const zoom = ref(15);
const centerValue = ref([104.07331, 30.664252]); // 初始中心点
const polyOption = {
  draggable: false,
  visible: true,
  edit: false,
  path: [],
  fillColor: mapData.fillColor,
  strokeOpacity: 1,
  fillOpacity: 0.5,
  strokeColor: mapData.fillColor,
  strokeWeight: 1,
  strokeStyle: 'dashed',
  strokeDasharray: [5, 5],
}

const markers = ref([]) //标记点
let map = null;

//监听中心点
watch(() => props.center, (val) => {
  // console.log('监听中心点', val);
  if (val) {
    // console.log('map-center', val);
    if (val[0] != undefined) {
      centerValue.value = val
      nextTick(() => {
        addMarker(val[0], val[1])
      })
    }
  }
}, {
  immediate: true,
  deep: true
})

//监听区域
watch(() => props.area, (val) => {
  console.log('map-area', val);
  if (val && isArray(val)) {
    polygons.value = [] //置空区域数组
    paths.value = []
    if (JSON.stringify(val).slice(0, 3) !== "[[[") { //如果传过来的不是[[[就不继续执行
      return;
    } else {
      val.forEach(item => { //遍历区域数组
        let i = cloneDeep(polyOption)
        i.path = item
        polygons.value.push(i)
        paths.value.push(item)
      })
    }
  }
}, {   immediate: true,deep: true })






const init = (e) => {  //初始化
  map = e;
}

function draw(e) { //有2个参数data,targer 第一个参数为绘制生成的对应数据，第二个为绘制的图形对象
  console.log("有2个参数data,targer", e);
  let i = cloneDeep(polyOption)
  i.path = e
  polygons.value.push(i)
  paths.value.push(e)
  emits("update:area", paths.value)
}

const addnode = (e) => {   // 鼠标操作折线图 调整 增加 删除
  console.log("鼠标操作折线图 调整 增加 删除", e)
  setTimeout(() => {
    paths.value = polygons.value.map(item => {
      return item.path
    })
    // console.log(paths.value);
    emits("update:area", paths.value)
  }, 500)
}

function mouseOver(e) { // 鼠标经过
  console.log("鼠标经过", e);
  polygons.value[e].fillColor = mapData.hoverFillColor;
}

function mouseOut(index) { //鼠标移出
  console.log("鼠标移出", index);
  polygons.value[index].fillColor = mapData.fillColor;
}

function dblclick(index) { //鼠标左键双击事件
  console.log("鼠标左键双击事件", index);
  if (props.isEdit) {
    polygons.value[index].edit = !polygons.value[index].edit;
    // call();
  }
}

const dragends = e => {  //点标记拖拽移动结束触发事件
  console.log("点标记拖拽移动结束触发事件", e.lnglat);
  centerValue.value = [e.lnglat.lng, e.lnglat.lat];
  emits("update:center", centerValue.value);

};

const addMarker = (lon, lat) => {  //标记点
  let position = {
    position: [lon, lat]
  }
  // console.log(position);
  markers.value = [position]
}

const onchange = (value) => { //选择地址
   console.log("选择", value);
  search.value = value.name
  toMap(value)
}

const remoteMethod = (query) => { //自定义远程搜索方法
  // if (query) {
  //   autoInput(query)
  //   setTimeout(() => {
  //     loading.value = false
  //   }, 200)
  // }
}

const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  const results = queryString
  autoInput(results, cb)
}

// 获取搜索信息
function autoInput(query, cb) {
  map.plugin('AMap.AutoComplete', function () {
    var autoOptions = {}
    var placeSearch = new AMap.AutoComplete(autoOptions);
    placeSearch.search(query, function (status, result) {
      // 搜索成功时，result即是对应的匹配数据
      // console.log("获取搜索信息",result);
      place.value = [];
      if (result === "NO_PARAMS" || status === "error" || status === "no_data") return
      if (result.info.toLowerCase() === "ok" && result.tips.length > 0) {
        result.tips.forEach(item=>{
          // console.log(item);
            if (item.location) {
               place.value.push(item);
              setTimeout(() => {
          cb(place.value)
        }, 500)
            }
        })

      }
    })
  })
}

function createPolygon() { //开始停止添加区域
  console.log(markers.value);
  console.log(centerValue.value);
  createArea.value = !createArea.value
  if (createArea.value) {
    createType.value = "polygon"
  } else {
    createType.value = ""
  }
}

const toMap = (item) => {  //进行标点
  addMarker(item.location.lng, item.location.lat)
  centerValue.value = [item.location.lng, item.location.lat]
  emits("update:center", centerValue.value)
}
</script>
